{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "I0929 22:26:32.452105 139811974653760 file_utils.py:39] PyTorch version 1.0.1 available.\n",
      "I0929 22:26:32.947797 139811974653760 modeling_xlnet.py:194] Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex .\n"
     ]
    }
   ],
   "source": [
    "import logging\n",
    "import torch\n",
    "import transformers\n",
    "from transformers import GPT2Tokenizer, GPT2Config, GPT2Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.0.1 2.0.0\n"
     ]
    }
   ],
   "source": [
    "print(torch.__version__, transformers.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "device = torch.device(\"cuda:3\" if torch.cuda.is_available() else \"cpu\")\n",
    "vocab_file = \"./pre-models/gpt2-vocab.json\"\n",
    "merges_file = \"./pre-models/gpt2-merges.txt\"\n",
    "\n",
    "config_file = \"./pre-models/gpt2-config.json\"\n",
    "# model_file = \"./pre-models/gpt2-pytorch_model.bin\"\n",
    "\n",
    "model_dir = \"./pre-models\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Encoder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([ 8241,   373,  5395,   367, 19069,  5633,  5395,   367, 19069,   373,\n",
      "          257])\n"
     ]
    }
   ],
   "source": [
    "# 激活logger 看更多信息\n",
    "logging.basicConfig(level=logging.INFO)\n",
    "\n",
    "# 加载预训练模型gpt2tokenizer (vocabulary)\n",
    "tokenizer = GPT2Tokenizer(vocab_file=vocab_file, merges_file=merges_file)  # 还可以输入unk_token、bos_token、eos_token\n",
    "# 编码文本\n",
    "text = \"Who was Jim Henson ? Jim Henson was a \"\n",
    "indexed_tokens = tokenizer.encode(text)\n",
    "\n",
    "# 装换为 a PyTorch tensor\n",
    "tokens_tensor = torch.tensor([indexed_tokens])\n",
    "print(tokens_tensor[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Decoder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "I0928 01:17:28.144083 140176204212032 modeling_utils.py:334] loading weights file ./pre-models/pytorch_model.bin\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预测文本： Who was Jim Henson? Jim Henson was a man\n",
      "predicted word:  man\n"
     ]
    }
   ],
   "source": [
    "# 使用 预测文本的下一个单词\n",
    "# 加载本地预训练模型(weights)\n",
    "config = GPT2Config.from_json_file(json_file=config_file)\n",
    "model = transformers.GPT2LMHeadModel.from_pretrained(model_dir, from_tf=False, config=config)\n",
    "\n",
    "# 设置模型的eval模式以停用dropout模块\n",
    "# This is IMPORTANT to have reproductible【可繁殖？】 results during evaluation!\n",
    "model.eval()\n",
    "\n",
    "# 使用GPU\n",
    "tokens_tensor = tokens_tensor.to(device)\n",
    "model.to(device)\n",
    "\n",
    "# 预测\n",
    "with torch.no_grad():\n",
    "    outputs = model(tokens_tensor)\n",
    "    predictions = outputs[0]\n",
    "\n",
    "# 预测文本的下一个单词\n",
    "predicted_index = torch.argmax(predictions[0, -1, :]).item()\n",
    "predicted_text = tokenizer.decode(indexed_tokens + [predicted_index])\n",
    "print(\"预测文本：\", predicted_text)\n",
    "print(\"predicted word:\", tokenizer.decode([predicted_index]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 方法二"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "?GPT2Tokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
